<?php
/**
 * Created by PhpStorm.
 * User: Daxu
 * Date: 2018/1/3
 * Time: 17:45
 */

namespace App\Http\Controllers\Api\Admin\CMS;


use App\Http\Controllers\Controller;
use App\Http\Requests\ColumnRequest;
use App\Http\Resources\ColumnResource;
use App\Models\Column;
use Illuminate\Http\Request;
class ColumnController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {

        $keyword = $request->get('keyword', '');
        $query = Column::query();
        $models = $query->when($keyword, function ($queryString) use ($keyword) {
            return $queryString->where('name', 'like', '%' . $keyword . '%');
        })->orderByDesc('id')->get()->toArray();
        return $this->generateTree($this->getListArray($models));
    }
    public function getListArray($items)
    {
        $tree = array();
        foreach ($items as $item) {
            $tree[$item['id']] = $item;
        }
        return $tree;
    }

    public function generateTree($items)
    {
        $tree = array();
        foreach ($items as $item) {
            if (isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['children'][] = &$items[$item['id']];
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }

    /**
     * @param ColumnRequest $request
     * @return ColumnResource
     */
    public function store(ColumnRequest $request)
    {
        $data = $request->all();
        $model = new Column();
        $model->fill($data);
        $model->save();
        $father = $this->findModel($model->parent_id);
        if ($father) {
            $model->key = $father->key . $model->id . "-";
        } else {
            $model->key = "-" . $model->id . "-";
        }
        $model->save();
        return new ColumnResource($model);
    }

    /**
     * @param $id
     * @return ColumnResource
     */
    public function show($id)
    {
        $model = $this->findModel($id);

        return new ColumnResource($model);
    }

    /**
     * @param ColumnRequest $request
     * @param $id
     * @return ColumnResource
     */
    public function update(ColumnRequest $request, $id)
    {
        $data = $request->all();
        $model = $this->findModel($id);
        $model->fill($data);
        $model->save();
        return new ColumnResource($model);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        $model->delete();
        return response()->json(['state'=>'success']);

    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function findModel($id){
        $model = Column::query()->where('id',$id)->first();
        return $model;
    }
}